<template>
<!--问卷管理-->
    <div>
        <ToolBar>
            <el-button type="primary" icon="el-icon-plus" size="small" @click="add">添加问卷</el-button>
            <div class="searchBar">
                <el-input placeholder="请输入内容" v-model="fieldVal" size="small" style="width: 340px" clearable>
                    <el-select v-model="field" slot="prepend" placeholder="请选择" style="width:100px">
                        <el-option label="标题" value="title"></el-option>
                    </el-select>
                    <el-button @click="search" slot="append" icon="el-icon-search"></el-button>
                </el-input>
            </div>
        </ToolBar>
        <el-table v-loading="loading" :data='papers' border style="width: 100%">
            <el-table-column :formatter='formatCtime' align="center" label="创建时间" width="180">
            </el-table-column>
            <el-table-column prop="title" align="center" label="标题" width="180">
            </el-table-column>
            <el-table-column prop="users[0].username" align="center" label="创建人">
            </el-table-column>
            <el-table-column prop="classes[0].class_name" align="center" label="班级">
            </el-table-column>
            <el-table-column label="操作" align="center" :render-header="tableAction" width="300">
                <template slot-scope="{row}">
                    <el-popover placement="top-start" width="50" trigger="hover" content="编辑" class="btnPop">
                        <el-button slot="reference" type="primary" icon="el-icon-edit" size='mini' @click='edit(row.id)' style="backgroundColor:rgb(238, 250, 255);color:#3C8DBC"></el-button>
                    </el-popover>
                    <el-popover placement="top-start" width="50" trigger="hover" content="删除" class="btnPop">
                        <el-button slot="reference" type="danger" icon="el-icon-delete" size='mini' @click='del(row.id)' style="backgroundColor:rgb(255,255,255);color:#f56c6c"></el-button>
                    </el-popover>
                    <el-popover placement="top-start" width="50" trigger="hover" content="发布" class="btnPop">
                        <el-button slot="reference" type="success" icon="el-icon-upload" size='mini' @click='publish(row.id)' style="backgroundColor:rgba(103,194,58,.1);color:#67c23a;borderColor:rgba(103,194,58,.2)"></el-button>
                    </el-popover>
                    <el-popover placement="top-start" width="50" trigger="hover" content="分析" class="btnPop">
                        <el-button slot="reference" type="warning" icon="el-icon-question" size='mini' @click='analysis(row.id)' style="backgroundColor:rgba(230,162,60,.1);color:#e6a23c;borderColor:rgba(230,162,60,.2)"></el-button>
                    </el-popover>
                </template>
            </el-table-column>
        </el-table>
        <el-pagination background layout="prev, pager, next ,sizes" :total="total" :page-sizes='[5,10,20]' :page-size='pageSize' :current-page.sync='currentPage' @current-change='currentChange' @size-change='sizeChange'></el-pagination>
        <!--编辑问卷-->
        <el-dialog title="编辑问卷" :visible="editFormVisible" width="40%" :show-close="false">
            <el-form :model="editForm" status-icon label-position="right" ref="editForm" :rules="rules">
                <el-form-item label="标题" label-width="70px" prop="title">
                    <el-input v-model="editForm.title" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="班级" label-width="70px" prop="class_id">
                    <el-select v-model="editForm.class_id" placeholder="请选择">
                        <el-option v-for="cls in classes" :key="'cls_'+cls.id" :label="cls.class_name+'班'" :value="cls.id"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="选项" label-width="70px" prop="item">
                    <el-select v-model="editForm.item" placeholder="请选择">
                        <el-option v-for="item in items" :key="'items_'+item.id" :label="item.item_name" :value="JSON.stringify(item.children)"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="大纲：" label-width="70px">
                    <el-button type="text" @click="out">点击选择大纲</el-button>
                    <div v-if="editForm.content[0]">
                        已选择：
                        <el-tag v-for="val in editForm.content" :key="val.id">{{val.outline_name}}</el-tag>
                    </div>
                    <!--大纲弹出框-->
                    <el-dialog title="选择大纲" :visible="outFormVisible" width="70%" height="500px" :show-close="false" append-to-body>
                        <el-tree ref="tree" node-key="id" @check-change="checkChange" :render-after-expand="false" :show-checkbox='true' :data="outlines" accordion>
                            <div class="tree-details" slot-scope="{data}">
                                <el-row type="flex">
                                    <el-col style="flex: 1">
                                        <span style="font-size: 13px">
                                            <span style="color: #3c8dbc">【 </span>{{data.outline_name}}
                                            <span style="color: #3c8dbc"> 】</span>
                                        </span>
                                    </el-col>
                                </el-row>
                            </div>
                        </el-tree>
                        <div slot="footer" class="dialog-footer">
                            <el-button @click="cancel1">取 消</el-button>
                            <el-button type="primary" @click="submit">确 定</el-button>
                        </div>
                    </el-dialog>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="cancel('editForm')">取 消</el-button>
                <el-button type="primary" @click="save('editForm',editForm.id)">确 定</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
import ToolBar from '@/components/ToolBar.vue';
import HelpHint from '@/components/HelpHint.vue';
import moment from 'moment'
export default {
    data() {
        return {
            searchParams: {
                postTitle: '',
                postType: '',
                postStatus: 'published',
            },
            id: '',
            field: '',
            fieldVal: '',
            papers: [],
            pageSize: 5,
            currentPage: 1,
            total: 0,
            loading: false,
            editFormVisible: false,
            outFormVisible: false,
            editForm: {
                title: '',
                class_id: '',
                item: '',
                content: []
            },
            classes: [],
            items: [],
            outlines: [],
            rules: {
                title: [
                    { required: true, message: '请输入标题', trigger: 'blur' },
                    { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
                ],
                class_id: [
                    { required: true, message: '请选择班级', trigger: 'blur' },
                ],
                item: [
                    { required: true, message: '请选择选项', trigger: 'blur' },
                ]
            },
        }
    },
    created() {
        this.getPapers();
    },
    methods: {
        getPapers() {
            this.loading = true;
            this.axios.get('/papers', {
                params: {
                    pageSize: this.pageSize,
                    currentPage: this.currentPage,
                    field: this.field,
                    fieldVal: this.fieldVal,
                }
            }).then((ret) => {
                this.loading = false;
                const { data } = ret.data;
                this.total = data.total;
                this.papers = data.rows;
            }).catch(() => { })
        },
        currentChange() {
            this.getPapers();
        },
        sizeChange(size) {
            this.pageSize = size;
            this.getPapers();
        },
        search() {
            this.getPapers();
        },
        add() {
            this.$router.push({ name: 'paperAdd' })
        },
        edit(id) {
            this.id = id;
            this.editFormVisible = true;
            this.getClasses();
            this.getItems();
            this.getPaper1(id);
        },
        del(id) {
            this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
                center: true
            }).then(() => {
                this.axios.delete('/papers/del/' + id).then(() => {
                    this.getPapers();
                    this.$message({
                        type: 'success',
                        message: '删除成功!'
                    });
                }).catch(() => { })
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消删除'
                });
            });
        },
        formatCtime: function(row) {
            return moment(row.ctime).format('YYYY-MM-DD HH-mm-ss')
        },
        publish(id) {
            this.$router.push({ name: 'publish', params: { id } })
        },
        analysis(id) {
            this.$router.push({ name: 'analysis', params: { id } })
        },
        handleClick(row) {
            this.$alert(row, '标题名称', {
                confirmButtonText: '确定',
                callback: action => {
                }
            });
        },
        tableAction() {
            return this.$createElement('HelpHint', {
                props: {
                    content: '编辑问卷 / 删除问卷 / 发布问卷 / 分析问卷  '
                }
            }, '操作');
        },
        getPaper1(id) {
            this.axios.get('/papers/' + id).then((ret) => {
                let { title, class_id, item, content } = ret.data.data;
                this.editForm.title = title
                this.editForm.class_id = class_id;
                this.editForm.item = JSON.stringify(item);
            })
        },
        //大纲
        getOutlines(id) {
            this.axios.get('/outlines').then((ret) => {
                this.outlines = ret.data.data;
                this.axios.get('/papers/' + id).then((ret) => {
                    let { content } = ret.data.data;
                    this.$refs.tree.setCheckedNodes(content);
                })
            })
        },
        //选像
        getItems() {
            this.axios.get('/items').then((ret) => {
                this.items = ret.data.data;
            })
        },
        //班级
        getClasses() {
            this.axios.get('/classes', {
                params: {
                    currentPage: 1,
                    pageSize: 9999,
                }
            }).then((ret) => {
                this.classes = ret.data.data.rows;
            })
        },
        checkChange(node, flag) {
            if (node.children.length == 0) {
                if (flag) {
                    this.editForm.content.push(node);
                } else {
                    let i = this.editForm.content.indexOf(node);
                    this.editForm.content.splice(i, 1);
                }
            }
        },
        save(form) {
            this.$refs[form].validate((valid) => {
                if (valid) {
                    if (this.editForm.content.length == 0) {
                        this.$message.error('至少选择一个大纲哦');
                    } else {
                        this.axios.put('/papers/edit/' + this.id, {
                            title: this.editForm.title,
                            class_id: this.editForm.class_id,
                            item: this.editForm.item,
                            content: JSON.stringify(this.editForm.content),
                        }).then(() => {
                            this.getPapers();
                            this.editFormVisible = false;
                        }).catch(() => { })
                    }
                } else {
                    this.$message.error('错了哦，请正确填写表单内容');
                }
            });
        },
        cancel() {
            this.editFormVisible = false;
        },
        cancel1() {
            this.outFormVisible = false;
        },
        submit() {
            if (this.editForm.content.length == 0) {
                this.$message.error('至少选择一个大纲哦');
            } else {
                this.outFormVisible = false;
            }
        },
        out() {
            this.outFormVisible = true;
            this.getOutlines(this.id);
        }
    },
    components: {
        ToolBar, HelpHint
    }
}
</script>
<style lang="less">
.el-select {
    display: block;
}

.searchBar {
    display: flex;
    float: right;
}

.el-tree-node {
    .el-tree-node__content {
        height: 50px;
        line-height: 50px;
    }
}

.el-popover--plain {
    padding: 5px;
}

.el-popover {
    min-width: 0;
    text-align: center;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0);
}

.el-table .cell .btnPop {
    margin: 10px;
}

.el-tag {
    margin-right: 10px;
}
</style>
